<template>
  <div class="departments-container">
    <div class="header">
      <h3>部门管理</h3>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加部门
      </el-button>
    </div>

    <el-table :data="departments" style="width: 100%" v-loading="loading">
      <el-table-column prop="departmentId" label="部门ID" width="120" />
      <el-table-column prop="name" label="部门名称" width="180" />
      <el-table-column prop="manager.name" label="部门经理" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加部门' : '编辑部门'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="部门ID" prop="departmentId">
          <el-input v-model="form.departmentId" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="部门经理" prop="managerId">
          <el-select v-model="form.managerId" placeholder="请选择部门经理">
            <el-option
              v-for="employee in employees"
              :key="employee.employeeId"
              :label="employee.name"
              :value="employee.employeeId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../api'

const departments = ref([])
const employees = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

const form = ref({
  departmentId: '',
  name: '',
  manager: null
})

const rules = {
  departmentId: [
    { required: true, message: '请输入部门ID', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  manager: [
    // 移除required验证
  ]
}

const loadData = async () => {
  loading.value = true
  try {
    departments.value = await api.get('/departments')
    employees.value = await api.get('/employees')
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
  loading.value = false
}

const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    departmentId: '',
    name: '',
    manager: null
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = {
    departmentId: row.departmentId,
    name: row.name,
    manager: row.manager?.employeeId || null
  }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该部门吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await api.delete(`/departments/${row.departmentId}`)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          ...form.value,
          managerId: form.value.manager?.employeeId || null
        }
        if (dialogType.value === 'add') {
          await api.post('/departments', submitData)
          ElMessage.success('添加成功')
        } else {
          await api.put(`/departments/${form.value.departmentId}`, submitData)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.departments-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 